package fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.itboye.hutoubenjg.R;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import activity.order.ActivityChangeThePrice;
import activity.order.MapActivity;
import activity.order.WeiXiuOkActivity;
import activity.personal.ImageVieMaxActivyt;
import base.BaseFragment;
import base.MyApplcation;
import bean.order_bean.RepairBean;
import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;
import presenter.SysTemPresenter;
import util.utls.BasePtr;
import util.utls.ByAlert;
import util.utls.Const;
import util.utls.IsUtilUid;
import util.utls.SPUtils;
import util.utls.TimeFormat;
import util.utls.UIAlertView;
import util.utls.XImageLoader;
import util.volley.ResultEntity;

/**
 * 订单
 */

public class OrderFragemnt extends BaseFragment implements Observer {
    private Button btnOrder, btnOrders, btnOrdert;
    private LocationClient locClient;
    double dblng;
    double dblat;
    SysTemPresenter presenter;
    RepairBean bean;
    RelativeLayout reyoutMap;

    private TextView tvMatter, tvaddress, tvOrderData, tvAddreXiangXi, tvaddressphone;
    String status;
    PtrFrameLayout commend_anchor_ptr;
    LinearLayout one;
    LinearLayout lintou;
    RelativeLayout twowo;
    LinearLayout img0;
    private UIAlertView uiAlertView;

    String uid;
    @Override
    public int initView() {
        return R.layout.fragment_order;
    }

    @Override
    public void onMyActivityCreated() {
        uid = (String) SPUtils.get(MyApplcation.ctx, null, Const.ID, "");
        InitLocation();
        presenter = new SysTemPresenter(this);
        bean = new RepairBean();
        presenter.onRepair(uid, "7");
        Log.d("werwerwerwe", IsUtilUid.isReparl());
        BasePtr.setPagedPtrStyle(commend_anchor_ptr);//设置上拉下拉刷新
        commend_anchor_ptr.setPtrHandler(new PtrDefaultHandler2() {//刷新的监听事件
            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                presenter.onRepair(uid, "7");
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                presenter.onRepair(uid, "7");
            }
        });
        commend_anchor_ptr.autoRefresh();

        // 广播发过来有新的订单  刷新界面
        IntentFilter filter1 = new IntentFilter("weixiu");
        getActivity().registerReceiver(shuaxinReceiver, filter1);
        // 广播发过来有新的订单  刷新界面
        IntentFilter filter2 = new IntentFilter("EXITCHANGE");
        getActivity().registerReceiver(shuaxinReceiver, filter2);

        //登录的广播
        IntentFilter filter = new IntentFilter("chaingLogin");
        getActivity().registerReceiver(loginReceiver, filter);
    }
    BroadcastReceiver loginReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            uid = (String) SPUtils.get(MyApplcation.ctx, null, Const.ID, "");
            presenter.onRepair(uid, "7");
        };
    };
    BroadcastReceiver shuaxinReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            presenter.onRepair(uid, "7");

        };
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(shuaxinReceiver);
        getActivity().unregisterReceiver(loginReceiver);
    }

    @Override
    public void onStart() {
        super.onStart();
        presenter.onRepair(uid, "7");
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {

            case R.id.btnOrder:

                if (status == null || status == "") {
                    one.setVisibility(View.GONE);
                } else if (status.equals("1")) {
                    btnOrder.setText("报价");
                    intent = new Intent(getActivity(), ActivityChangeThePrice.class);
                    intent.putExtra("id", bean.getId());
                    intent.putExtra("url", "重报价");
                    startActivity(intent);
                } else if (status.equals("2")) {
                    btnOrder.setText("重报价");
                    intent = new Intent(getActivity(), ActivityChangeThePrice.class);
                    intent.putExtra("id", bean.getId());
                    intent.putExtra("url", "重报价");
                    startActivity(intent);
                } else if (status.equals("3")) {
                    btnOrder.setText("等待司机支付");
                } else if (status.equals("4")) {
                    btnOrder.setText("维修完成");
                    Intent intent1 = new Intent(getActivity(), WeiXiuOkActivity.class);
                    intent1.putExtra("title", "维修");
                    intent1.putExtra("url", "维修完成");
                    startActivity(intent1);
                } else if (status.equals("5")) {
                    btnOrder.setText("待司机确认完成");
                    ByAlert.alert("等待司机确认");
                }

                break;
            case R.id.reyoutMap:
                intent = new Intent(getActivity(), MapActivity.class);
                intent.putExtra("mobile", bean.getMobile());
                intent.putExtra("addres", bean.getAddress());
                intent.putExtra("lat", bean.getLat());
                intent.putExtra("lng", bean.getLng());
                startActivity(intent);
//                MyPermission.CheckPermission(getActivity(), Manifest.permission.READ_PHONE_STATE);
                break;
        }
    }


    //    在Activity的onRequestPermissionResult回调函数中做处理：
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

//        switch(requestCode) {
//            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
//            case 1:
//            if(grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                // 获取到权限，作相应处理（调用定位SDK应当确保相关权限均被授权，否则可能引起定位失败）
//                Intent intent = new Intent(getActivity(), MapActivity.class);
//                intent.putExtra("mobile", bean.getMobile());
//                intent.putExtra("addres", bean.getAddress());
//                intent.putExtra("lat", bean.getLat());
//                intent.putExtra("lng", bean.getLng());
//                startActivity(intent);
//            } else{
//                // 没有获取到权限，做特殊处理
//                ByAlert.alert("拒绝了权限");
//            }
//            break;
//            default:
//                break;
//        }
    }

    public void onStop() {
        // TODO Auto-generated method stub
        locClient.stop();
        super.onStop();
    }

    private void InitLocation() {
        locClient = new LocationClient(getActivity());
        locClient.registerLocationListener(new MyLocationListener());
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);// 打开gps
        option.setCoorType("bd09ll");// 设置坐标类型
        option.setAddrType("all");
        option.setScanSpan(1000);//
        locClient.setLocOption(option);
        locClient.start();
    }

    @Override
    public void update(Observable observable, Object data) {
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            IsUtilUid.tianjia(entity);
            if (entity.getEventType() == presenter.Repair_success) {

                bean = (RepairBean) entity.getData();
                if (bean.getRepair_status() == null || bean.getRepair_status() == "") {
                    one.setVisibility(View.GONE);

                    lintou.setVisibility(View.VISIBLE);
                    twowo.setVisibility(View.GONE);
                    btnOrder.setVisibility(View.GONE);
                    btnOrdert.setVisibility(View.GONE);
                    btnOrders.setVisibility(View.GONE);
                } else {
                    lintou.setVisibility(View.GONE);
                    twowo.setVisibility(View.VISIBLE);
                    btnOrder.setVisibility(View.VISIBLE);
                    one.setVisibility(View.VISIBLE);


                    String str = bean.getImages();// 原始字符串

                    String[] arrayStr = new String[]{};// 字符数组
                    List<String> lists = new ArrayList<String>();// list

                    arrayStr = str.split(",");// 字符串转字符数组
                    lists = java.util.Arrays.asList(arrayStr);// 字符数组转list
                    String[] storeStr = lists.toArray(new String[lists.size()]);// list转成字符数组
                    img0.removeAllViews();
        /* 输出字符数组的值 */
                    for (final String s : arrayStr) {
                        System.out.println(s);


                        if (s == null || s.equals("")) {
                            img0.setVisibility(View.GONE);
                        } else if (storeStr.length <= 0) {

                            img0.setVisibility(View.GONE);
                        } else if (storeStr.length >= 1) {
                            img0.setVisibility(View.VISIBLE);
                            View v = LayoutInflater.from(MyApplcation.ctx).inflate(R.layout.layout_items, null);
                            ImageView img1 = (ImageView) v.findViewById(R.id.img1);
                            XImageLoader.load(Const.IMAGE_HEAD + s, img1);
                            ViewGroup.MarginLayoutParams layoutParams = new ViewGroup.MarginLayoutParams(
                                    ViewGroup.MarginLayoutParams.WRAP_CONTENT,
                                    ViewGroup.MarginLayoutParams.WRAP_CONTENT);
                            layoutParams.setMargins(5, 5, 5, 5);
                            img1.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {

                                    Intent intent = new Intent(getActivity(), ImageVieMaxActivyt.class);
                                    intent.putExtra("id", s);
                                    startActivity(intent);
                                }
                            });
                            img0.addView(v, layoutParams);
                        }

                    }

                    tvMatter.setText(bean.getRepair_name() + "" + bean.getVehicle_name());
                    tvaddress.setText(bean.getDetail());

                    tvOrderData.setText(TimeFormat.DateFormat(bean.getCreate_time()));
                    tvAddreXiangXi.setText(bean.getAddress());
                    tvaddressphone.setText(bean.getMobile());
                    tvaddressphone.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(Intent.ACTION_DIAL);
                            Uri data = Uri.parse("tel:" + bean.getMobile());
                            intent.setData(data);
                            startActivity(intent);
                        }
                    });
                    commend_anchor_ptr.refreshComplete();//设置刷新完成
                    status = bean.getRepair_status();
                    if (status.equals("1")) {
                        btnOrder.setText("报价");

                    } else if (status.equals("2")) {
                        btnOrder.setText("重报价");
                    } else if (status.equals("4")) {
                        btnOrders.setVisibility(View.VISIBLE);
                        btnOrder.setVisibility(View.GONE);
                        btnOrders.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                uiAlertView = new UIAlertView(getActivity(), "温馨提示！", "待司机确认维修完成后,维修款将进入您的余额。如果司机忘记确认,一小时后也可到账", "是", "取消");
                                uiAlertView.show();
                                uiAlertView.setClicklistener(new UIAlertView.ClickListenerInterface() {
                                    @Override
                                    public void doLeft() {
                                        presenter.onWieXiuWancheng(uid, bean.getId(), "7");
                                        uiAlertView.dismiss();
                                    }

                                    @Override
                                    public void doRight() {
                                        uiAlertView.dismiss();
                                    }
                                });

                                // showProgressDialog("加载中..",true);
                            }
                        });

                    } else if (status.equals("3")) {
                        btnOrder.setText("等待司机支付");
                    } else if (status.equals("6")) {
                        btnOrder.setText("维修完成");

                    } else if (status.equals("5")) {
                        btnOrder.setText("待司机确认完成");
                    }

                    try {
                        closeProgressDialog();
                    } catch (Exception ex) {

                    }
                }

            } else if (entity.getEventType() == presenter.Wancheng_success) {

                ByAlert.alert(entity.getData() + "");
                btnOrdert.setVisibility(View.VISIBLE);
                btnOrders.setVisibility(View.GONE);
                btnOrder.setVisibility(View.GONE);
//                try {
//                    closeProgressDialog();
//                } catch (Exception ex) {
//
//                }
            }
        }
    }


    /**
     * 实现实位回调监听
     */
    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {

            Log.d("jindu", location.getLatitude() + "唯独" + location.getLongitude() + "");
            locClient.stop();
//            double mLat1 = 30.3216650000; // point1纬度
//            double mLon1 = 120.3416610000; // point1经度
//
//            double mLat2 = 30.3239790000;// point2纬度
//            double mLon2 = 120.3855860000;// point2经度
//            String str = location.getAddrStr();
            dblng = location.getLongitude();//纬度
            dblat = location.getLatitude();//精度
//            double distance = BiaduMaps.GetShortDistance(mLon1, mLat1, location.getLongitude(), location.getLatitude());
//            DecimalFormat df   = new DecimalFormat("######0.00");
//             ble=distance/1000;
//            Log.d("保留小数:", df.format(ble)+"km");

        }


    }

}
